package database;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import jfoo.Preferences;

import audio.AudioFile;
import audio.MP3;

// singleton
public class Database implements Serializable, Runnable {

	private static final long serialVersionUID = 2441169557509897830L;
	private static final Database database = new Database();

	HashMap<String, AudioFile> db;

	private Database() {
		new Thread(this).start();
	}

	public static Database getInstance() {
		return database;
	}

	public HashMap<String, AudioFile> getDb() {
		return db;
	}

	public void clear() {
		db.clear();
	}

	public void scanLibrary() {
		new ScanLibrary(Preferences.getInstance().getLibraryFolder()).start();
	}

	public ArrayList<AudioFile> search(String s) {

		Set<Map.Entry<String, AudioFile>> entries = db.entrySet();
		Iterator<Map.Entry<String, AudioFile>> iterator = entries.iterator();

		ArrayList<AudioFile> arrayList = new ArrayList<AudioFile>();

		while (iterator.hasNext()) {
			Map.Entry<String, AudioFile> entry = iterator.next();
			AudioFile audioFile = entry.getValue();
			StringTokenizer st = new StringTokenizer(s);
			boolean found = false;
			while (st.hasMoreElements()) {
				String token = st.nextElement().toString();
				if (audioFile.contains(token)) {
					found = true;
				} else {
					found = false;
					break;
				}
			}
			if (found)
				arrayList.add(entry.getValue());

		}
		return arrayList;

	}

	public void add(File f) {
		// System.out.println(f.getAbsolutePath());
		if (f.isDirectory()) {
			File[] liste = f.listFiles();
			for (int i = 0; i < liste.length; i++) {
				add(liste[i]);
			}
		} else {
			if (AudioFile.isAudioFile(f)) {
				try {
					this.db.put(f.getPath(), new MP3(f));
				} catch (IOException e) {
					System.out.println(f.getPath() + "couldn't be found");

				}
			}
		}
	}

	@Override
	public void run() {
		File ft = new File("database.data");
		if (ft.exists()) {

			try {
				ObjectInputStream lecteur = new ObjectInputStream(
						new FileInputStream(ft));
				db = ((HashMap<String, AudioFile>) lecteur.readObject());

			} catch (java.io.InvalidClassException ex) {
				System.out.println("la base de donnée ne sont plus a jour");
				db = new HashMap<String, AudioFile>();

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			db = new HashMap<String, AudioFile>();
		}

	}

	class ScanLibrary extends Thread {
		String path;

		public ScanLibrary(String path) {
			this.path = path;
		}

		public void run() {
			try {
				File f = new File(path);
				add(f);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
